package com.amarsoft.leetcode;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Stack;

public class Solution {
    public boolean isPalindrome(int x) {
        int count = 0;
        int que = 0;
        if (x < 0) {
            return false;
        }
        char[] chars = String.valueOf(x).toCharArray();
        que = chars.length / 2;
        if (chars.length % 2 != 0) {
            que ++ ;
        }
        if (chars.length == 1) {
            return true;
        }
        if (chars.length % 2 == 0) {
            for (int i = 0; i < chars.length / 2; i++) {
                if (chars[i] == chars[chars.length - 1 - i]) {
                    count++;
                }
            }
        } else {
            for (int i = 0; i <= chars.length / 2; i++) {
                if (chars[i] == chars[chars.length - 1 - i]) {
                    count++;
                }
            }
        }
        if (que == count) {
            return true;
        }
        return false;
    }

    public boolean isValid(String s) {
        //使用栈来解决括号匹配的问题
        //一个栈从字符串的左边进行入栈操作，一个栈从字符串的右边进行入栈操作，然后同时弹出，如果弹出的字符串不同则返回false
        Stack stack = new Stack<Character>();
        Map map = new HashMap<Character, Character>();
        map.put('[', ']');
        map.put('{', '}');
        map.put('(', ')');
        char[] chars = s.toCharArray();
        if (chars.length % 2 != 0) {
            return false;
        }
        //遇到开括号进行入栈操作,遇到一个闭括号将进行出栈 如果栈顶元素对应闭括号元素则成功 遍历完后 栈中不应该剩下元素
       for (int i = 0; i < chars.length; i++) {
           if (map.containsKey(chars[i])) {
               stack.push(chars[i]);
           } else {
               if (stack.size() == 0)
                   continue;
               if(!map.get((Character)stack.pop()).equals(chars[i])) {
                   return false;
               }
           }
       }
       if (stack.size() == 0) {
           return true;
       }
       return false;
    }

    public static void main(String[] args) {
        Solution solution = new Solution();
        //System.out.println(solution.isPalindrome(11));
        System.out.println(solution.isValid("){"));
    }
}
